<template>
  <div class="article-management">
    <div class="page-header">
      <div class="header-left">
        <el-button type="primary" @click="router.push('/')">
          <el-icon><ArrowLeft /></el-icon>
          返回主页
        </el-button>
      </div>
      <div class="header-center">
        <h2>文章管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建文章
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="articleList"
      style="width: 100%"
      border
    >
      <el-table-column label="封面图片" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            fit="cover"
            style="width: 80px; height: 80px"
            :preview-src-list="[scope.row.imageUrl]"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="plantId" label="ID" width="80" />
      <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
      <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button
            :type="scope.row.status === 1 ? 'warning' : 'success'"
            size="small"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '取消发布' : '发布' }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.plantId ? '编辑文章' : '新建文章'"
      width="70%"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="editForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
          />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="article-image-upload"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="editForm.imageUrl" :src="editForm.imageUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="info" @click="submitEdit(false)">保存草稿</el-button>
          <el-button type="primary" @click="submitEdit(true)">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, ArrowLeft } from '@element-plus/icons-vue'
import { getAllArticles, createArticle, updateArticle, deleteArticle, updateArticleStatus } from '@/api/article'

const router = useRouter()
const loading = ref(false)
const articleList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const editDialogVisible = ref(false)
const editForm = ref({
  plantId: null,
  title: '',
  content: '',
  imageUrl: ''
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString()
}

// 获取文章列表
const getArticleList = async () => {
  loading.value = true
  try {
    const res = await getAllArticles()
    console.log('获取到的文章列表数据:', res)
    // 直接处理返回的数组数据
    if (Array.isArray(res)) {
      articleList.value = res.map(item => ({
        plantId: item.plantId,
        title: item.name,
        content: item.description,
        status: item.status || 0,
        createTime: item.createdAt,
        updateTime: item.createdAt,
        imageUrl: item.imageUrl,
        userId: item.userId
      }))
      total.value = articleList.value.length
    } else {
      ElMessage.error('获取文章列表失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error(error?.message || '获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getArticleList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getArticleList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getArticleList()
}

// 新建文章
const handleCreate = () => {
  editForm.value = {
    plantId: null,
    title: '',
    content: '',
    imageUrl: ''
  }
  editDialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  editForm.value = {
    plantId: row.plantId,
    title: row.title,
    content: row.content,
    imageUrl: row.imageUrl
  }
  editDialogVisible.value = true
}

// 处理文章状态变更
const handleStatusChange = async (article) => {
  try {
    await ElMessageBox.confirm(
      `确定要${article.status === 1 ? '取消发布' : '发布'}该文章吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('准备更新文章状态:', {
      plantId: article.plantId,
      currentStatus: article.status,
      newStatus: article.status === 1 ? 0 : 1
    })
    
    const res = await updateArticleStatus(article.plantId, article.status === 1 ? 0 : 1)
    console.log('更新文章状态响应:', res)
    
    ElMessage.success('操作成功')
    getArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新文章状态失败:', error)
      ElMessage.error('操作失败：' + (error.response?.data?.message || error.message || '未知错误'))
    }
  }
}

// 删除文章
const handleDelete = async (article) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该文章吗？此操作不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('准备删除文章:', {
      plantId: article.plantId
    })
    
    const res = await deleteArticle(article.plantId)
    console.log('删除文章响应:', res)
    
    ElMessage.success('删除成功')
    getArticleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message || '未知错误'))
    }
  }
}

// 提交编辑
const submitEdit = async (isPublish) => {
  try {
    if (!editForm.value.title || !editForm.value.content) {
      ElMessage.warning('请填写必填项')
      return
    }
    
    const data = {
      name: editForm.value.title,
      description: editForm.value.content,
      status: isPublish ? 1 : 0,
      imageUrl: editForm.value.imageUrl
    }
    
    if (editForm.value.plantId) {
      // 更新文章
      await updateArticle(editForm.value.plantId, data)
      ElMessage.success(isPublish ? '发布成功' : '保存成功')
    } else {
      // 创建新文章
      await createArticle(data)
      ElMessage.success('创建成功')
    }
    
    editDialogVisible.value = false
    getArticleList()
  } catch (error) {
    console.error('保存文章失败:', error)
    ElMessage.error('保存失败')
  }
}

// 处理图片上传成功后的逻辑
const handleImageSuccess = (response, file) => {
  // 这里可以根据需要处理上传成功后的逻辑
  console.log('图片上传成功:', response, file)
}

// 处理图片上传前的逻辑
const beforeImageUpload = (file) => {
  // 这里可以根据需要处理上传前的逻辑
  console.log('图片上传前:', file)
  return true // 返回true表示允许上传
}

onMounted(() => {
  getArticleList()
})
</script>

<style scoped>
.article-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.header-left {
  flex: 1;
}

.header-center {
  flex: 2;
  text-align: center;
}

.header-center h2 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
}

.header-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.article-image-upload {
  text-align: center;
}

.article-image-upload .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.article-image-upload .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.article-image-upload .avatar-uploader-icon:hover {
  border-color: #409EFF;
}
</style> 